package com.ruhua.java.api;

import com.ruhua.java.dao.Article;
import com.ruhua.java.dao.Region;
import com.ruhua.java.dto.ArticleDTO;
import com.ruhua.java.dto.RegionDTO;
import com.ruhua.java.dto.SuccessDTO;
import com.ruhua.java.repository.RegionRepository;
import com.ruhua.java.vo.ResVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;


@RestController
public class RegionController {

    @Autowired
    RegionRepository regionRepository;

    @GetMapping("/index/get_address")
    public ResVO<List> get_address() {
        List<Region> list=regionRepository.findAll();
        return ResVO.go(list);
    }

    @PostMapping("/cms/admin/add_region")
    public ResVO<String> add_region(@RequestBody @Validated RegionDTO dto){
        Long level = dto.getPid()>0?2l:1l;
        Region item = Region.builder()
                .mergerName(dto.getName())
                .name(dto.getName())
                .pid(dto.getPid())
                .level(level)
                .build();
        regionRepository.save(item);
        return ResVO.go();
    }


    @PostMapping("/cms/admin/edit_region")
    public SuccessDTO up(@RequestBody @Validated RegionDTO dto){
        Region item=regionRepository.findOneById(dto.getId());
        item.setName(dto.getName());
        regionRepository.save(item);
        return new SuccessDTO();
    }

    @DeleteMapping("/cms/admin/del_region")
    public ResVO<String> del(@RequestParam Long id){
        regionRepository.deleteById(id);
        return ResVO.go();
    }
}
